package com.marketing.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.marketing.auth.entity.Resource;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 资源Mapper接口
 */
@Mapper
public interface ResourceMapper extends BaseMapper<Resource> {

    /**
     * 根据用户ID查询用户可访问的资源
     * @param userId 用户ID
     * @return 资源列表
     */
    @Select("SELECT DISTINCT r.* FROM sys_resource r " +
            "INNER JOIN sys_permission p ON r.id = p.resource_id " +
            "INNER JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "INNER JOIN sys_user_role ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.status = 1 AND p.status = 1 " +
            "ORDER BY r.sort_order ASC, r.id ASC")
    List<Resource> selectResourcesByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID查询菜单资源
     * @param userId 用户ID
     * @return 菜单资源列表
     */
    @Select("SELECT DISTINCT r.* FROM sys_resource r " +
            "INNER JOIN sys_permission p ON r.id = p.resource_id " +
            "INNER JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "INNER JOIN sys_user_role ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.status = 1 AND p.status = 1 " +
            "AND r.resource_type = 'MENU' " +
            "ORDER BY r.sort_order ASC, r.id ASC")
    List<Resource> selectMenusByUserId(@Param("userId") Long userId);

    /**
     * 查询所有启用的资源
     * @return 资源列表
     */
    @Select("SELECT * FROM sys_resource WHERE status = 1 ORDER BY sort_order ASC, id ASC")
    List<Resource> selectEnabledResources();

    /**
     * 根据父级ID查询子资源
     * @param parentId 父级ID
     * @return 子资源列表
     */
    @Select("SELECT * FROM sys_resource WHERE parent_id = #{parentId} AND status = 1 ORDER BY sort_order ASC, id ASC")
    List<Resource> selectByParentId(@Param("parentId") Long parentId);

    /**
     * 根据资源编码查询资源
     * @param resourceCode 资源编码
     * @return 资源信息
     */
    @Select("SELECT * FROM sys_resource WHERE resource_code = #{resourceCode} AND status = 1")
    Resource selectByResourceCode(@Param("resourceCode") String resourceCode);
}